using System;
using System.Collections;
using System.Web.UI.WebControls;
using PHSRAG.Insight21.Common.Pages;
using PHSRAG.Insight21.Context;
using PHSRAG.Insight21.Policy;

namespace PHSRAG.Insight21.Personnel
{
    /// <summary>
    /// The DeleteDistribution class supports the DeleteDistribution.aspx page
    /// It allows the user to delete a salary distribution along with the associated splits
    /// </summary>
    public partial class DeleteDistribution : NoCachePage
    {
        #region Constants

        private const string ClosePopupJSKey = "ClosePopup_7B7E6CD1-5D8C-47F1-B226-784226E4B8F7";
        private const string SplitEndDateLabelName = "splitEndDate";
        private const string SplitIDKey = "SplitID_7B7E6CD1-5D8C-47F1-B226-784226E4B8F7";
        private const string SplitStartDateLabelName = "splitStartDate";
        private const string ToBePaidLabelName = "toBePaid";

        #endregion

        #region Instance variables (Private)

        private ICachePolicy cachePolicy;
        private ICachePolicy pageCachePolicy;
        private ViewStateCachePolicy viewStataCachePolicy;

        #endregion

        #region Private properties

        /// <summary>
        /// Get the Personnel details object from the cache
        /// Throw an exception if there is some error in retrieving the object from cache
        /// </summary>
        private PersonnelDetails PersonnelDetailsInstance
        {
            get
            {
                PersonnelDetails personnelDetails =
                    ResultsCache.GetObject(cachePolicy, PersonnelDetails.CacheKey) as PersonnelDetails;

                if (personnelDetails == null)
                {
                    throw new Exception
                        (@"Error deleting a salary distribution, failed to retrieve personnel details.");
                }

                return personnelDetails;
            }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Handler for the event raised when the page is being loaded.
        /// Retrieve the split id from the pageCachePolicy and save it in viewState
        /// Databind all the controls on the page
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnPageLoad(object sender, EventArgs e)
        {
            annunciator.Message = string.Empty;
            annunciator.Title = string.Empty;

            if (!IsPostBack)
            {
                try
                {
                    Hashtable dictionary = pageCachePolicy.GetCachedObject(Keys.IncomingDataKey) as Hashtable;

                    int splitID = Convert.ToInt32(Request.
                        QueryString[Constants.QueryStringSplitIDKey]);

                    SalaryDistribution salaryDistrib =
                        PersonnelDetailsInstance.SalaryDistribs.GetSalaryDistribution(splitID);

                    txtTitle.Text = salaryDistrib.Title;
                    annualRate.Text = string.Format("{0:c}", salaryDistrib.AnnualRate);
                    percentEffort.Text = salaryDistrib.PercentEffort.ToString();

                    splits.DataSource = salaryDistrib.Splits;
                    splits.DataBind();

                    viewStataCachePolicy.Cache(SplitIDKey, splitID);

                    cancelDelete.Attributes.Add("onclick", "javascript:window.close();");
                }
                catch (Exception ex)
                {
                    annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
                }
            }
        }

        /// <summary>
        /// Handler for the event raised when the delete button is clicked on the screen
        /// Remove the PersonnelDetailsInstance from the cache to enable the PersonnelDetails page to reload the data
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnDelete(object sender, EventArgs e)
        {
            try
            {
                PersonnelDetailsInstance.SalaryDistribs.
                    GetSalaryDistribution(Convert.ToInt32(viewStataCachePolicy.GetCachedObject(SplitIDKey))).
                    DeleteDistribution(Utility.DataAccess.ConnectionString
                        , ((UserContext) cachePolicy.GetCachedObject(UserContext.CacheKey)).DomainUserId);

                ResultsCache.PurgeObject(cachePolicy);

                //This is used in the per details page for tracking
                pageCachePolicy.Cache(Keys.TransactionFlagKey, true);

                Page.ClientScript.RegisterClientScriptBlock(GetType(),
                    ClosePopupJSKey,
                    "<script language='javascript'>window.opener.document.location.href='PersonnelDetails.aspx';window.close();</script>");
            }
            catch (Exception ex)
            {
                Utility.ExceptionReport.WriteToEventLog
                    ("Delete Distribution", ex, true, Utility.ExceptionReport.ReportType.Error);

                annunciator.Message = Utility.ExceptionReport.GetExceptionInfo(ex, false);
            }
        }

        /// <summary>
        /// Handler for the event raised when a row in the repeater is databound.
        /// Bind the labels inside the Repeater with the data from the split object 
        /// </summary>
        /// <param name="sender">Control which raised the event</param>
        /// <param name="e">Argument associated with the event</param>
        private void OnSplitsItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            RepeaterItem splitItem = e.Item;

            if (splitItem.ItemType == ListItemType.AlternatingItem ||
                splitItem.ItemType == ListItemType.Item)
            {
                DistributionSplit split = (DistributionSplit) splitItem.DataItem;

                ((Label) splitItem.FindControl(SplitStartDateLabelName)).Text = split.EffectiveDate;
                ((Label) splitItem.FindControl(SplitEndDateLabelName)).Text = split.ExpirationDate;
                ((Label) splitItem.FindControl(ToBePaidLabelName)).Text = split.ToBePaid.ToString("c");
            }
        }

        #endregion

        #region Web Form Designer generated code

        /// <summary>
        /// Handler for the event raised when the page is being initialized.
        /// Instantiate the viewStateCachePolicy using the ViewState of the page.
        /// </summary>
        /// <param name="e">Argument associated with the event</param>
        protected override void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);

            cachePolicy = (Policy.ICachePolicy) Session[Policy.Names.CachePolicyKey];
            viewStataCachePolicy = new PHSRAG.Insight21.Policy.ViewStateCachePolicy(this.ViewState);
            pageCachePolicy = (Policy.ICachePolicy) Session[Policy.Names.PageCachePolicyKey];
        }

        /// <summary>
        /// Required method for Designer support 
        /// </summary>
        private void InitializeComponent()
        {
            this.Load += new EventHandler(this.OnPageLoad);
            this.deleteDistrib.Click += new EventHandler(this.OnDelete);
            this.splits.ItemDataBound += new RepeaterItemEventHandler(this.OnSplitsItemDataBound);
        }

        #endregion
    }
}